# backend/utils.py
import logging
from db import connection_pool

logger = logging.getLogger("utils")

WAKE_WORD = "小爱"
INTERRUPT_WORD = "小爱小爱"

def detect_keyword(text: str):
    if INTERRUPT_WORD in text:
        return "interrupt"
    if WAKE_WORD in text:
        return "wake"
    return None

def save_llm_fragment(conv_id: int, role: str, text: str, audio_path: str, segment_index: int):
    """
    Save one LLM fragment into MySQL history table.
    """
    cnx = None
    cursor = None
    try:
        cnx = connection_pool.get_connection()
        cursor = cnx.cursor()
        cursor.execute(
            """
            INSERT INTO history (conv_id, role, content, audio_path, duration, segment_index)
            VALUES (%s, %s, %s, %s, %s, %s)
            """,
            (conv_id, role, text, audio_path or "", 0.0, segment_index)
        )
        cnx.commit()
        return True
    except Exception:
        logger.exception("save_llm_fragment failed")
        if cnx:
            cnx.rollback()
        return False
    finally:
        if cursor:
            cursor.close()
        if cnx:
            cnx.close()
